package com.mright.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mright.model.LoginModel;
import com.mright.service.AccountService;

@Controller
@RequestMapping("/account")
public class AccountController {

	@Autowired
	private AccountService accountService;

	@GetMapping("/login")
	public String index() {
		return "account/login";
	}

	@PostMapping("/login")
	public String login(String userName, String passWord) {
		LoginModel loginModel = new LoginModel();
		loginModel.setUserName(userName);
		loginModel.setPassWord(passWord);
		try {
			boolean loginFlag = accountService.login(loginModel);
			if (loginFlag) {
				// shiro加入身份验证
				Subject subject = SecurityUtils.getSubject();
				UsernamePasswordToken token = new UsernamePasswordToken(loginModel.getUserName(),
						loginModel.getPassWord());
				subject.login(token);
				return "account/success";
			}

			return "account/failed";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "account/failed";
		}
	}
}
